package com.helloapp.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.helloapp.dao.UserDao;
import com.helloapp.dao.impl.UserDaoImpl;
import com.helloapp.entity.User;

/**
 * 这个采用配置式方式设置URL 地址为/Login2Servlet
 * 
 * @author ZTE
 *
 */
public class Login2Servlet extends HttpServlet {

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//request.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String remember = request.getParameter("remember");
		System.out.println(username);
		System.out.println(password);
		System.out.println(remember);
		// 1. 加载驱动
		UserDao userDao = new UserDaoImpl();
		User u = userDao.getByUsernameAndPassword(username, password);
		// 判断用户名与密码是否正确
		if (u.getUsername() != null) {
			request.getSession().setAttribute("username", username);
			if ("true".equals(remember)) {
				Cookie c = new Cookie("remember", username);
				// 设置Cookie有效时间为3600秒
				c.setMaxAge(3600);
				response.addCookie(c);
			} else {
				// 清除Cookie
				Cookie[] cookies = request.getCookies();
				if (cookies != null && cookies.length > 0) {
					for (Cookie c : cookies) {
						if (c.getName().equals("remember")) {
							c.setMaxAge(0);
							response.addCookie(c);
						}
					}
				}
			}
			request.getSession().removeAttribute("error");
			response.sendRedirect("main.jsp");
		} else {
			request.getSession().setAttribute("error", "用户名或密码错误");
			response.sendRedirect("login.jsp");
		}
	}
}
